package session

import (
	"github.com/patrickmn/go-cache"
	"strings"
	"time"
	"unicode/utf8"
	"wechat/gpt/client/conf"
)

type IUserSession interface {
	GetUserSessionContext(userId string) string
	SetUserSessionContext(userId string, question, reply string)
	ClearUserSessionContext(userId string, msg string) bool
}

type userSessionImpl struct {
	cache *cache.Cache
}

// NewUserService 创建新的业务层
func NewUserSession() IUserSession {
	return &userSessionImpl{cache: cache.New(time.Second*conf.GetConfig().SessionTimeout, time.Minute*10)}
}

// GetUserSessionContext 获取用户会话上下文
func (s *userSessionImpl) GetUserSessionContext(userId string) string {
	sessionContext, ok := s.cache.Get(userId)
	if !ok {
		return ""
	}
	return sessionContext.(string)
}

// SetUserSessionContext 设置用户会话上下文文本
func (s *userSessionImpl) SetUserSessionContext(userId, question, reply string) {
	value := question + "\n" + reply
	s.cache.Set(userId, value, time.Second*conf.GetConfig().SessionTimeout)
}

// ClearUserSessionContext 清空GPT上下文 接收文本中包含`下一个问题`
func (s *userSessionImpl) ClearUserSessionContext(userId string, msg string) bool {
	if strings.Contains(msg, "下一个问题") && utf8.RuneCountInString(msg) < 20 {
		s.cache.Delete(userId)
		return true
	}
	return false
}
